package org.example.servlet;

import org.example.DAO.BlogCommentDAO;
import org.example.entity.BlogComment;
import org.example.DAO.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

@WebServlet("/blog/comment/add")
public class BlogCommentAddServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/plain");
        resp.setCharacterEncoding("UTF-8");
        HttpSession session = req.getSession(false);

        // 1. 校验登录状态
        if (session == null || session.getAttribute("userId") == null) {
            resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            resp.getWriter().write("用户未登录");
            return;
        }
        Integer userId = (Integer) session.getAttribute("userId");

        // 2. 获取参数
        String blogId = req.getParameter("blogId");
        String content = req.getParameter("content");
        String parentId = req.getParameter("parentId");
        if (blogId == null || content == null || content.trim().isEmpty()) {
            resp.setStatus(HttpServletResponse.SC_BAD_REQUEST);
            resp.getWriter().write("参数缺失或内容为空");
            return;
        }

        // 3. 构造评论对象
        BlogComment comment = new BlogComment();
        comment.setUserId(userId);
        comment.setBlogId(blogId);
        comment.setContent(content.trim());
        comment.setParentId(parentId);
        comment.setUsername((String) session.getAttribute("username"));
        comment.setAvatar((String) session.getAttribute("avatar"));

        // 4. 数据库操作
        try (Connection conn = DBUtil.getConnection()) {
            BlogCommentDAO commentDAO = new BlogCommentDAO(conn);
            if (commentDAO.addComment(comment)) {
                resp.getWriter().write("评论成功");
            } else {
                resp.getWriter().write("评论失败");
            }
        } catch (SQLException e) {
            e.printStackTrace();
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            resp.getWriter().write("服务器错误：" + e.getMessage());
        }
    }
}